package com.jt;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Random;

@SpringBootApplication
public class consumer_RunApp {
    public static void main(String[] args) {
        SpringApplication.run(consumer_RunApp.class,args);
    }


    @Bean
    public RestTemplate restTemplate()
    {
        return  new RestTemplate();
    }

    @Bean
    @LoadBalanced
    public RestTemplate loadBalancedRestTemplate(){
        return new RestTemplate();
    }

    @CrossOrigin
    @RestController
    public  class  ConsumerContoller
    {
        @Value("${spring.application.name}")
        private  String serviceId;

        @Autowired
        private RestTemplate loadBalancedRestTemplate;

        @Autowired
        private LoadBalancerClient loadBalancerClient;

        @Autowired
        private  RestTemplate restTemplate;

           @GetMapping("/consumer/getPort")
            public  String doTestEach(){
//               //手动--静态负载均衡
//               //调用谁?sca-provider 多个url中的一个
//               String url1="http://localhost:8081/provider/echo/"+server;
//               String url2="http://localhost:8082/provider/echo/"+server;
//               String [] urls=new String[]{url1,url2};
//               int n=new Random().nextInt(2);
//               System.out.println("n:"+n);
//               return restTemplate.getForObject(urls[n],String.class);

               //基于LoadBalancerClient实现负载均衡
               String serviceId="sca-provider";
               ServiceInstance choose=loadBalancerClient.choose(serviceId);
               String ip=choose.getHost();
               int port=choose.getPort();
               //实现ip与port的动态变化
//               String url="http://"+ip+":"+port+"/provider/echo/"+port;
                String url=String.format("http://%s:%s/provider/echo/%s",ip,port,port);
                 return restTemplate.getForObject(url, String.class);
          }

          @GetMapping("/consumer/getPort2")
          public  String doRestEcho3()
          {
              String url=String.format("http://%s/provider/echo/%s","sca-provider",serviceId);
              return  loadBalancedRestTemplate.getForObject(url, String.class);
          }
    }
}
